package com.ym521.logdog.crash

import com.ym521.logdog.core.ILogDogEngine
import kotlin.concurrent.thread

/**
 *@author Ym
 *E-mail: 2435970206@qq.com
 *createTime:2023/10/29
 *explain: Crash处理
 */
internal class CrashHandlerEngine : ICrashHandlerEngine {
    private var callback: CrashExceptionCallBack? = null

    companion object {
        fun build(): CrashHandlerEngine {
            return CrashHandlerEngine()
        }
    }

    override fun onCrashHandler(logDog: ILogDogEngine) {
        Thread.setDefaultUncaughtExceptionHandler { thread, e ->
            printerLog(logDog, thread, e)
            thread {
                //保证日志的正常写入
                Thread.sleep(2 * 1000)
                if (callback == null) {
                    defaultHandler()
                } else {
                    if (thread.name == "main")
                        callback?.onMainThreadException(e)
                    else
                        callback?.onChildThreadException(e)
                }
            }.start()
        }
    }

    private fun printerLog(logDog: ILogDogEngine, thread: Thread, e: Throwable) {
        logDog.crashLog("Crash", "【 Thread:%log 】    【 Throwable:%log 】", thread.name, e)
    }

    override fun setCustomHandler(callback: CrashExceptionCallBack?) {
        this.callback = callback
    }

    private fun defaultHandler() {
        android.os.Process.killProcess(android.os.Process.myPid())
    }
}